<template>
  <div class="userlist">
    <div class="content-header">
      <!--      <h1>文件管理</h1>-->
    </div>


    <div class="filter-container">
      <!--      //这里v-model要改。。。-->
      <el-input placeholder="标题" v-model="searchData" style="width: 150px;padding:15px"
                class="filter-item"></el-input>

<!--      <el-select v-if="$route.query.to==='单元化管理'" v-model="chooseLine" placeholder="线名"-->
<!--                 style="float: left;width: 150px;padding:15px" clearable>-->
<!--        <el-option v-for="Line in Lines" :key="Line.lId" :value="Line.linename" :label="Line.linename"></el-option>-->
<!--      </el-select>-->

      <el-button @click="getMassage()" class="dalfBut">查询</el-button>
      <el-button type="primary" class="butT" @click="getAddDialog">新建</el-button>
      <el-button @click="fromCommit()" type="danger">删除选中项</el-button>
    </div>

    <template>
      <el-table
          :data="files.filter(data => !search || data.title.toLowerCase().includes(search.toLowerCase()))"
          stripe
          style="width: 100%"
          current-row-key="id"
          @selection-change="handleSelectionChange"
          height="440px">

        <el-table-column
            type="selection"
            style="margin-right: 100px"
            width="50">
        </el-table-column>

        <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center">
        </el-table-column>

        <el-table-column
            prop="title"
            label="标题"
            width=”100“
            align="center">
        </el-table-column>

        <el-table-column
            prop="uploadTime"
            label="日期"
            width=“100”
            align="center">
        </el-table-column>


<!--        <el-table-column-->
<!--            prop="fclass"-->
<!--            label="类型"-->
<!--            width="150"-->
<!--            align="center">-->
<!--        </el-table-column>-->

        <el-table-column
            prop="fileName"
            label="文件名"
            width="150"
            align="center">
        </el-table-column>

        <!--        <el-table-column-->
        <!--            prop="userName"-->
        <!--            label="用户名"-->
        <!--            width= "150"-->
        <!--            align="center">-->
        <!--        </el-table-column>-->

        <el-table-column
            v-if="$route.query.to==='单元化管理'"
            prop="linename"
            label="线名"
            width="150"
            align="center">
        </el-table-column>

        <el-table-column label="操作" align="center" width="200">

          <template slot-scope="scope">

            <!-- <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button> -->
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>

          </template>

        </el-table-column>

      </el-table>
    </template>


    <div class="add-form">
      <!--        编辑弹出框 -->
      <el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit" width="31%">

        <el-form ref="dataEditForm" :model="formData" :rules="rules2" label-position="right" label-width="100px">

          <el-row>


            <el-form-item label="id" prop="id" hidden="true">
              <el-input v-model="formData.id"/>
            </el-form-item>


          </el-row>

          <el-row>
            <el-form-item label="标题" prop="title">

              <el-input v-model="formData.title"/>

            </el-form-item>
          </el-row>

          <el-row>

            <el-form-item label="文件名" prop="fileName">

              <el-input v-model="formData.fileName"/>

            </el-form-item>

          </el-row>
<!--          <el-row v-if="$route.query.to==='单元化管理'">-->
<!--            <el-select v-model="formData.linename" placeholder="请选择线名">-->
<!--              <el-option v-for="Line in Lines" :key="Line.lId" :value="Line.linename"-->
<!--                         :label="Line.linename"></el-option>-->
<!--            </el-select>-->
<!--          </el-row>-->

        </el-form>

        <div slot="footer" class="dialog-footer">

          <el-button @click="cancel()">取消</el-button>

          <el-button type="primary" @click="handleEdit()">确定</el-button>

        </div>

      </el-dialog>
    </div>

    <br/>
    <br/>

    <div class="add">
      <!--        添加弹出框 -->
      <el-dialog title="文件信息" :visible.sync="dialogFormVisible" width="31%">
        <el-form :model="form" :rules="rules2" ref="form">

          <el-form-item>
            <el-upload
                class="upload-demo"
                ref="upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                accept=".xlsx,.xls,.doc,.docx,.pdf"
                :limit="1"
                :http-request="uploadFileAndParams"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <!--              <el-button  style="margin-left: 10px;" size="small" type="success" plain @click="dialogFormVisible = true">编辑文档信息</el-button>-->
              <div slot="tip" class="el-upload__tip">能上传xlsx/xls/doc/docx/pdf文件，且不超过20Mb</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
            <el-input v-model="form.title" autocomplete="off"></el-input>
          </el-form-item>
          <!-- <el-form-item label="文件名" :label-width="formLabelWidth" prop="fileName">
            <el-input v-model="form.fileName" autocomplete="off"></el-input>
          </el-form-item> -->
          <!--          <el-form-item label="用户id" :label-width="formLabelWidth" prop="pwd">-->
          <!--            <el-input v-model="form.userId" autocomplete="off"></el-input>-->
          <!--          </el-form-item>-->
<!--          <el-form-item label="线名" :label-width="formLabelWidth" prop="linename">-->
<!--            <el-select v-model="form.linename" placeholder="请选择线名" style="float: left" :disabled="disabled" clearable>-->
<!--              <el-option v-for="Line in Lines" :key="Line.lId" :value="Line.linename"-->
<!--                         :label="Line.linename"></el-option>-->
<!--              &lt;!&ndash;              <el-option label="普通用户" value="1"></el-option>&ndash;&gt;-->
<!--              &lt;!&ndash;              <el-option label="管理员" value="2"></el-option>&ndash;&gt;-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" v-preventClick>提交</el-button>

        </el-form>
      </el-dialog>
    </div>

    <!--分页组件-->
    <div class="pagination-container">

      <el-pagination
          class="pagiantion"

          @current-change="handleCurrentChange"

          :current-page="pagination.currentPage"

          :page-size="pagination.pageSize"

          layout="total, prev, pager, next, jumper"

          :total="pagination.total">

      </el-pagination>

    </div>
  </div>
</template>
<script>

export default {
  name: "FileManage",
  data() {
    return {
      disabled: this.$route.query.to !== '单元化管理',
      search: '',
      searchData: '',
      chooseLine: '',
      test: '',
      params: new FormData(),
      fileList: [],
      files: [],
      file: null,

      Lines: [],
      form: {
        title: '',
        class: '',
        linename: '无',
        userId: '',
        fileName: '',
        id: ''
      },
      //需要在需要检查的模板上填上":rules:xxxxx"，并在每一个需要检查的行中加入“prop”绑定数据。
      rules2: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        // class: [
        //   {required: true, message: '请输入类别', trigger: 'blur'},
        //   {min: 1, max: 50, message: '长度在 1 到 10 个字符', trigger: 'blur'}
        // ],
        // linename: [
        //   {required: true, message: '请选择线名', trigger: 'blur'},
        // ],
        fileName: [{required: true, message: '请输入文件名', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}]
      },
      formData: {},

      //控制添加弹出框
      dialogFormVisible: false,
      //控制编辑弹出框
      dialogFormVisible4Edit: false,


      radio: '1',

      //控制删除提示框
      centerDialogVisible: false,

      // dialogTableVisible: false,

      formLabelWidth: '120px',

      pagination: {//分页相关模型数据
        currentPage: 1,//当前页码
        pageSize: 10,//每页显示的记录数
        total: 0,//总记录数
        title: "",//查询条件

      }
    };

  },
  mounted() {
    this.getAll();
    // this.getLines();
  },

  methods: {
    //多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    fromCommit() {
      var param = ''
      for (var i = 0; i < this.multipleSelection.length; i++) {
        param += this.multipleSelection[i].id + ','
        // param.append("nId",this.multipleSelection[i].nId)
      }
      // console.log("parma:::::")
      // let params = new URLSearchParams();
      // let a = this.multipleSelection;
      this.$axios.post("/file/file/deleteFile?list=" + param).then(
          (res) => {
            if (res.data.code === 200) {
              this.$message.success("删除成功");
            } else if (res.data.code === 401) {
              this.$message.error("无权限!");
            } else {
              this.$message.error("删除失败!");
            }
          }
      ).finally(() => {
        //2.重新加载数据
        this.getAll();
      })
      // this.getAll();
    },

    //删除用户信息
    handleDelete(row) {
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
        this.$axios.post("/file/file/deleteFile?list=" + row.id).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");
          } else if (res.data.code === 401) {
            this.$message.error("无权限！");
          } else {
            this.$message.error("数据同步失败，自动刷新");
          }
        }).finally(() => {
          //2.重新加载数据
          this.getAll();
        });
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },
    // 添加文件上传
    // 添加文件上传
    submitUpload() {
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };
      this.$refs.upload.submit();
      if (this.params.get('file') === null) {
        this.$message.error("请选择文件")
        return
      }
      if(this.form.title === '' || this.form.title===null || this.form.title.length>50){
        this.$message.error("标题不能为空,且不能超过50个字符");
        return
      }
      // if(this.form.fileName === '' || this.form.fileName===null || this.form.fileName.length>50){
      //   this.$message.error("文件名不能为空,且不能超过50个字符");
      //   return
      // }

      // this.params.append("fclass", this.$route.query.to)
      this.params.append("userId", localStorage.getItem('authorId'))
      this.params.append("title", this.form.title)
      // this.params.append("fileName", this.form.fileName)
      // this.params.append("linename", this.form.linename);
      // this.params.append("ddate", '');

      this.$axios.post('/file/file/uploadFile', this.params, config).then((res) => {
        if (res.data.code === 200) {
          this.$message.success("添加成功！")
        } else if (res.data.code === 500) {
          this.$message.error("服务器错误，请联系管理员")
        } else if (res.data.code === 400) {
          this.$message.error("文件名重复！")
        }
      }).finally(() => {
        this.$refs.upload.clearFiles();
        //2.重新加载数据
        this.getAll();
      })
      this.dialogFormVisible = false;
    },


    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.params.delete("file")
    },
    handlePreview(file) {
      console.log(file);
    },
    uploadFileAndParams(param) {
      this.params.append("file", param.file)
    },

    getMassage() {
      // if (this.chooseLine === '') {
      //   this.getAll()
      // } else {
      //   this.$axios.get("/file/selectFile?curpage=" + this.pagination.currentPage + "&pagesize=" + this.pagination.pageSize + "&linename=" + this.chooseLine).then((res) => {
      //     this.pagination.total = res.data.data.total;
      //     let a = res.data.data.records;
      //     this.files = a;
      //   });
      // }
      let a = this.searchData
      this.search = a;
    },


    //提交添加表单信息
    // submitForm() {
    //   this.$refs.form.validate((valid) => {
    //     if (valid) {
    //       this.add();
    //     } else {
    //       console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    //重置表单
    resetForm(form) {
      this.$refs[form].resetFields();
    },
    //获取所有用户信息
    getAll() {
      //发送异步请求
      this.$axios.get("/file/file/fileList?curpage=" + this.pagination.currentPage + "&pagesize=" + this.pagination.pageSize).then((res) => {
        console.log("filr!!!")

        this.pagination.total = res.data.data.records.length;
        console.log("filr!!w!")

        // res.data.data.records.forEach(function(item,index,self){
        //   self[index].ddate=item.ddate.substr(0,19)
        // })
        this.files = res.data.data.records;
        // console.log("filr!!!")
        // console.log(this.files)

        // console.log(res.data.data.records[0].ddate);
      });

      this.files=[{title:'测试文件1',uploadTime:'2023-5-10',fileName:'测试文件1'},{title:'测试文件2',uploadTime:'2023-5-10',fileName:'测试文件2'}]

    },
    getAddDialog(){
      // this.params.delete("fclass")
      this.params.delete("userId")
      this.params.delete("title")
      this.params.delete("fileName")
      // this.params.delete("linename");
      // this.params.delete("ddate");
      this.params.delete("file");
      this.form={title: '',
                class: '',
                linename: '无',
                userId: '',
                fileName: '',
                id: ''}
      this.dialogFormVisible=true
    },

    //切换页码
    handleCurrentChange(currentPage) {
      //修改页码值为当前选中的页码值
      this.pagination.currentPage = currentPage;
      //执行查询
      this.getAll();
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!');
      }
      return isLt2M;
    },
    //添加方法
    add() {
      let fd = new FormData();
      fd.append('file', this.file);

      //其他参数！。。。。。。
      // fd.append('')
      this.$axios.post("/addFile", fd).then((res) => {
        if (res.data.data === 200) {
          this.dialogFormVisible = false;
          this.$message.success("添加成功！");
        } else if (res.data == "0") {
          this.$message.error("添加失败！");
        } else if (res.data == "2") {
          this.$message.error("已存在同名文件!")
        }
      }).finally(() => {
        this.dialogFormVisible = false;
        this.getAll();
      });
    },

    //弹出编辑窗口回显文件信息
    handleUpdate(row) {
      this.dialogFormVisible4Edit = true
      let a = row;
      this.formData = a
    },

    //提交编辑结果
    handleEdit() {
      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      if(this.formData.title === '' || this.formData.title===null || this.formData.title.length>50){
        this.$message.error("标题不能为空,且不能超过50个字符");
        return
      }
      if(this.formData.fileName === '' || this.formData.fileName===null || this.formData.fileName.length>50){
        this.$message.error("文件名不能为空,且不能超过50个字符");
        return
      }
          let params = new FormData()
          params.append('title', this.formData.title)
          params.append('id', this.formData.id)
          params.append('fileName', this.formData.fileName)

          // if(this.$route.query.to==='单元化管理'){
          // }
          // params.append('linename', this.formData.linename)
          this.$axios.post("/file/modifyFile", params).then((res) => {
            //判断当前操作是否成功
            if (res.data.code === 200) {
              this.dialogFormVisible = false;
              this.$message.success("编辑成功！");
            } else if (res.data.code === 401) {
              this.$message.error("无权限！");
            } else if (res.data.code === 500) {
              this.$message.error("服务器错误，请联系管理员！");
            } else if (res.data.code === 400) {
              this.$message.error("无权限!")
            }

          }).finally(() => {
            //2.重新加载数据
            this.getAll();
          });
      //   }
      // });
    },
    //取消操作，关闭弹窗
    cancel() {
      // this.dialogFormVisible = false;
      this.dialogFormVisible4Edit = false;
      this.$message.info("当前操作取消");
    },
    //获取所有线名
    // getLines() {
    //   //发送异步请求
    //   this.$axios.get("/line/lineList").then((res) => {
    //     this.Lines = res.data.data;
    //   });
    //
    // }
  },

}

</script>
<style scoped>
.filter-container {
  text-align: left;
}

.filter-item el-input {
  padding: 10px;
}


</style>
